﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GemTowerDefence.Towers
{
  public class Tower : Sprite
  {
    #region Constants and Fields

    protected readonly Texture2D MissileTexture;
    protected float MissileTimer; // How long ago was a bullet fired
    protected List<Missile> Missiles = new List<Missile>();

    #endregion

    #region Constructors and Destructors

    public Tower(Texture2D texture, Texture2D missileTexture, Vector2 position)
      : base(texture, position)
    {
      MissileTexture = missileTexture;
    }

    #endregion

    #region Properties

    public int Damage { get; protected set; }

    public float Range { get; protected set; }

    public Enemy Target { get; protected set; }

    public virtual bool HasTarget
    {
      get { return Target != null; }
    }

    public bool IsSelected { get; set; }

    #endregion

    #region Public Methods

    public virtual void GetClosestEnemy(List<Enemy> enemies)
    {
      Target = null;
      float smallestRange = Range;

      foreach (Enemy enemy in enemies)
      {
        if (Vector2.Distance(Center, enemy.Center) < smallestRange)
        {
          smallestRange = Vector2.Distance(Center, enemy.Center);
          Target = enemy;
        }
      }
    }

/*
    public virtual void GetClosestEnemy(List<Enemy> enemies)
    {
      Target = null;

      var smallestRange = float.MaxValue;

      foreach (var enemy in enemies)
      {
        if (IsInRange(enemy.Center) == false)
          continue;

        float distance = enemy.WaypointCount + (enemy.DistanceToDestination / 32F);

        if (distance < smallestRange)
        {
          smallestRange = distance;
          Target = enemy;
        }
      }
    }
*/

    public bool IsInRange(Vector2 position)
    {
      return Vector2.Distance(Center, position) <= Range;
    }

    public override void Update(GameTime gameTime)
    {
      base.Update(gameTime);

      MissileTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;

      if (!HasTarget) return;

      if (!Target.IsDead)
        FaceTarget();
      if (!IsInRange(Target.Center) || Target.IsDead)
      {
        Target = null;
        MissileTimer = 0;
      }
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
      foreach (var bullet in Missiles)
        bullet.Draw(spriteBatch);
      base.Draw(spriteBatch);
      
      if (IsSelected)
        spriteBatch.Draw(Game.SelectionTexture, Center, null, Color.White, Rotation, Origin, 1.0f, SpriteEffects.None, 0);
    }

    #endregion

    #region Methods

    private void FaceTarget()
    {
      Vector2 direction = Center - Target.Center;
      direction.Normalize();

      Rotation = (float)Math.Atan2(-direction.X, direction.Y);
    }

    #endregion
  }
}